<template lang="pug">
  div
    header
      div.headBox
        div.logo
          img.logoImg(src="/static/Index/uu1.gif")
        nav
          router-link(v-bind:to="{name:'Index'}")
            span 首页
          router-link(v-bind:to="{name:'PublicCourse'}")
            span 公开课
          router-link(v-bind:to="{name:'ExcellentCourse'}")
            span.pidtu 精品课
              img(src="/static/Header/u644.gif")
          router-link(v-bind:to="{name:'WeChatCourse'}")
            span 微课
          router-link(v-bind:to="{name:'LiveBroadcastCourse'}")
            span.pidtu 直播课
              img(src="/static/Header/u638.gif")
          router-link(v-bind:to="{name:'Index'}")
            span 考试中心
        div.searchBox
          div.search
            div.inputBox
              input(type="text" v-model="sousuo" placeholder="请输入课程类型、课程类别、课程名称或授课教师" onfocus="this.placeholder=''" onblur="this.placeholder='请输入课程类型、课程类别、课程名称或授课教师'")
            div(@click="skip" ref="link").searchBtn
              <!--router-link(v-bind:to="{name:'SearchPage',params: {content:sousuo}}" @click.native="skip" ref="link").searchBtn -->
              span
                img(src="/static/Header/search.png")
              span 搜索
        div.loginBox
          div(v-if="status === 'center'")
            router-link(v-bind:to="{name:'PersonalCenter'}")
              img(src="/static/Index/头像_u627.png")
              span {{$store.state.currentUser.name}}
            span |
            span.loginRng(@click="logout") 退出
          div(v-if="status === 'login'")
            img(src="/static/Index/头像_u627.png")
            span.loginRng#enter(@click="thelog") 登 录
            span |
            span.loginRng#enroll(@click="registered") 注 册
          div#black(ref="black")
          div#black-box(ref="blacks")
            h1.h1 登 录
            el-form(v-model="loginFormModel").denglu
              el-form-item(label="用户名 :" label-position="right" label-width="80px")
                el-input(type="text" placeholder="请输入邮箱" v-model="loginFormModel.name" ref="loginFormName")
              el-form-item(label="密码 :" label-position="right" label-width="80px" @keyup.enter.native="_login")
                el-input(type="password" placeholder="请输入密码" show-password v-model="loginFormModel.password" ref="loginFormPass")
            div.tishi
              router-link(v-bind:to="{name:'PasswordBack'}").ziti 忘记密码?
            div.dengd(@click="_login") 登录
            div.disappear(@click="disappear")
              img(src="/static/Index/关闭按钮_u709.png")
          div#disappear-box(ref="disappears")
            h1.h1 注 册
            el-form(:model="registFormModel" :rules="registRules" ref="register").denglu
              el-form-item(label="昵称 :" label-position="right" label-width="90px" prop="name" )
                el-input(type="text" placeholder="12字符以内" v-model="registFormModel.name")
              el-form-item(label="密码 :" label-position="right" label-width="90px" prop="password")
                el-input(type="password" placeholder="4-8位,字母、数字不限,不可输入特殊字符" v-model="registFormModel.password" show-password)
              el-form-item(label="确认密码 :" label-position="right" label-width="90px" prop="passwordAgain")
                el-input(type="password" placeholder="再次输入密码" v-model="registFormModel.passwordAgain" show-password)
              el-form-item(label="邮箱 :" label-position="right" label-width="90px" prop="email")
                el-input(type="email" placeholder="请输入邮箱" v-model="registFormModel.email")
            div.registered(@click="register") 注册
            div.disappear(@click="regdisappear")
              img(src="/static/Index/关闭按钮_u709.png")
</template>

<script type="text/ecmascript-6">
  import {loginUrl, logoutUrl} from '../../config/global.toml'
  import Message from '../../common/message'
  import {mapMutations} from 'vuex'

  export default {
    name: 'KalixHeader',
    data() {
      // var validateName = (rule, value, callback) => {      }
      var validatePassword = (rule, value, callback) => {
        if (value !== undefined && value !== null && value !== '') {
          let valTrim = value.replace(/^\s+|\s+$/g, '')
          let reg = /^[a-zA-Z0-9]+$/
          if (reg.test(valTrim)) {
            callback()
          } else {
            callback(new Error('密码中包含特殊字符，请输入正确的密码'))
          }
        }
      }
      var validatePasswordAgain = (rule, value, callback) => {
        if (value !== undefined && value !== null && value !== '') {
          let valTrim = value.replace(/^\s+|\s+$/g, '')
          console.log()
          if (valTrim === this.registFormModel.password) {
            callback()
          } else {
            callback(new Error('两次密码不一致'))
          }
        } else {
          callback(new Error('请输入重复密码'))
        }
      }
      // var validateEmail = (rule, value, callback) => {}
      return {
        loginFormModel: {
          name: '',
          password: ''
        },
        sousuo: '',
        status: 'login',
        centerName: '',
        registFormModel: {
          name: '',
          password: '',
          passwordAgain: '',
          email: '',
          loginName: ''
        },
        registRules: {
          name: [
            {required: true, message: '昵称不能为空', trigger: 'blur'},
            {min: 0, max: 12, message: '长度在 12 个字符以内', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '密码不能为空', trigger: 'blur'},
            {min: 4, max: 8, message: '密码长度错误，请重新输入', trigger: 'blur'},
            {validator: validatePassword, trigger: 'blur'}
          ],
          passwordAgain: [
            {required: true, message: '请再次输入密码', trigger: 'blur'},
            {validator: validatePasswordAgain, trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱地址', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      ...mapMutations({
        setCurrentUser: 'setCurrentUser'
      }),
      skip() {
        if (this.sousuo.length !== 0) {
          this.$router.push({name: 'SearchPage', params: {content: this.sousuo}})
        }
      },
      proving() {
        this.registFormModel.email = this.registFormModel.email.replace(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$ /, '')
        this.registFormModel.email = this.registFormModel.email.replace('', '')
      },
      thelog() {
        this.$refs.black.style.display = 'block'
        this.$refs.blacks.style.display = 'block'
      },
      disappear() {
        this.$refs.black.style.display = 'none'
        this.$refs.blacks.style.display = 'none'
        this.loginFormModel.name = ''
        this.loginFormModel.password = ''
      },
      registered() {
        this.$refs.black.style.display = 'block'
        this.$refs.disappears.style.display = 'block'
      },
      regdisappear() {
        this.$refs.black.style.display = 'none'
        this.$refs.disappears.style.display = 'none'
        this.registFormModel.name = ''
        this.registFormModel.password = ''
        this.registFormModel.passwordAgain = ''
        this.registFormModel.email = ''
      },
      _login() {
        //  登录
        if (this.loginFormModel.name || this.loginFormModel.password !== '') {
          let that = this
          this.remoteLogin({
            'username': that.loginFormModel.name,
            'password': that.loginFormModel.password
          }).then(data => {
            console.log('aaaaaaaaaa', data)
            if (data.success) {
              this.$KalixCatch.save('id', data.user.id)
              this.$KalixCatch.save('access_token', data.access_token)
              this.$KalixCatch.save('user_token', data.user.token)
              this.$KalixCatch.save('user_name', data.user.name)
              this.$KalixCatch.save('loginname', that.loginFormModel.name)
              // 在缓存中记录最后登录时间，处理单用户登录需求
              let now = new Date().getTime()
              this.$KalixCatch._saveLocal('lastLoginTime', now)
              this.$KalixCatch.save('lastLoginTime', now)
              let signFlag = JSON.stringify(true)
              this.$KalixCatch.save('IS-SIGN-IN', signFlag)
              let path = JSON.parse(this.$KalixCatch.get('REDIRECT-URL'))
              if (path) {
                this.$nextTick(() => {
                  this.$router.push(path)
                })
              }
              this.$KalixMessage.success('登录成功')
              this.$KalixEventBus.$emit('LOGIN_SUCCESS')
              this.disappear()
              this.status = 'center'
              // this.centerName = that.loginFormModel.name
              // this.userName = this.$KalixCatch.get('user_name')
              this.setCurrentUser(data.user)
            } else {
              this.$refs.loginFormName.focus()
              this.$KalixMessage.error(data.message)
            }
          }).catch(error => {
            console.log('bbbbbbbbbbbbbbbbbbbb', error)
            this.$refs.loginFormName.focus()
            this.$KalixMessage.error(error.message)
          })
        } else {
          Message.warning('请输入用户名和密码')
        }
      },
      remoteLogin(_data) {
        console.log(`remote address is ${loginUrl}`)
        return this.$http.request({
          method: 'POST',
          url: loginUrl,
          transformRequest: [(data) => {
            // Do whatever you want to transform the data
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            return ret
          }],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          data: _data
        }).then((res) => {
          console.log('[kalix]-[login.js] remoteLogin function return data is: ', res.data)
          return Promise.resolve(res.data)
        })
      },
      register() { // 注册验证
        this.axios.request({
          method: 'GET',
          url: '/camel/rest/training/course/getValidationEmail',
          params: {
            email: this.registFormModel.email
          }
        }).then(res => {
          console.log('res.data.totalCount==============', JSON.parse(res.data).key)
          if (JSON.parse(res.data).key === '1') {
            this.registFormModel.loginName = this.registFormModel.name
            this.submit()
          } else {
            Message.info('邮箱已存在')
          }
        })
      },
      submit() {
        this.$refs.register.validate((valid) => {
          if (valid) {
            this.axios.request({
              method: 'POST',
              url: '/camel/rest/users/',
              data: this.registFormModel,
              params: {}
            }).then(response => {
              console.log('response:', response)
              // this.goLogin()
              if (response.data.success) {
                this.$KalixMessage.success('注册成功')
                this.regdisappear()
              } else {
                // 注册失败
                this.$KalixMessage.error('注册失败!' + response.data.msg)
              }
            })
          } else {
            this.$KalixMessage.error('请检查输入项！')
            return false
          }
        })
      },
      logout() {
        this.$http.get(logoutUrl, {}).then(response => {
          // console.log('LOGOUT+++++++++', logoutUrl)
          this.$KalixCatch.clear()
          this.$KalixCatch._clearLocal()
          this.status = 'login'
          this.$router.push({path: '/'})
        }).catch(err => {
          console.log(' ===== err ===== ', err)
          this.$KalixCatch.clear()
          this.$KalixCatch._clearLocal()
        })
      }
    },
    mounted() {
      this.centerName = this.$KalixCatch.get('loginname')
      console.log('this.centerName', this.$KalixCatch.get('loginname'))
      let signFlag = this.$KalixCatch.get('IS-SIGN-IN')
      this.status = signFlag ? 'center' : 'login'
      this.$KalixEventBus.$on('SHOW_LOGIN', this.thelog)
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  header
    width 100%
    height 80px
    box-shadow 0px 5px 10px #ddd
    margin-bottom 20px

  .headBox
    width 1200px
    height 100%
    margin 0 auto

  .logo
    width 100px
    height 100%
    float left

  .logoImg
    width 100%
    height 100%

  nav
    float left
    margin-left 40px
    height 80px
    line-height 80px
    font-size 18px

  nav span
    padding 0 14px

  nav span:hover
    color #008f95

  nav .pidtu
    position: relative

  nav .pidtu img
    position: absolute
    right -6px
    top -10px

  .searchBox
    float left
    padding 25px 0

  .search
    height 28px
    border 1px solid #ccc
    border-radius 25px
    padding-left 20px

  .inputBox input
    border none
    width 300px
    font-size 12px
    height 26px
    outline none

  .inputBox
    display inline-block

  .searchBtn
    width 80px
    height 28px
    padding-left 5px
    line-height 28px
    text-align center
    display inline-block
    background-color #008F95
    border-radius 25px
    float right
    color #fff
    cursor pointer

  .searchBtn span
    padding 0 3px
    float left
    height 28px
    line-height 28px
    display inline-block
    color #fff
    font-size 14px

  .searchBtn img
    width 20px
    height 22px
    margin-top 3px

  .loginBox
    display inline-block
    padding 26px 0
    padding-left 20px
    font-size 16px

  .loginBox span
    display inline-block
    height 28px
    float left
    line-height 28px
    padding 0 3px
    max-width 81px
    word-break keep-all /* 不换行 */
    white-space nowrap /* 不换行 */
    overflow hidden /* 内容超出宽度时隐藏超出部分的内容 */
    text-overflow ellipsis

  .loginBox img
    display inline-block
    float left
    width 20px
    height 22px
    margin-top 3px

  .loginRng
    cursor pointer

  .loginRng:hover
    color #008F95

  /*登录弹窗*/
  #black
    width 100%
    height 100%
    background-color #000
    position fixed
    top 0
    left 0
    z-index 998
    opacity 0.3
    display none

  #black-box
    width 600px
    height 380px
    background-color #fff
    position fixed
    left 50%
    top 50%
    margin-left -300px
    margin-top -190px
    z-index 999
    display none
    border-radius 10px

  .h1
    margin 40px auto
    margin-left 48%
    color #008F95
    font-size 26px
    font-weight 700

  .denglu
    width 400px
    margin 0 auto
    margin-bottom 20px

  .tishi
    width 350px
    margin 0 auto
    text-align right

  .ziti
    font-size 12px
    color #999
    cursor pointer

  .dengd
    width 200px
    height 34px
    background-color #008F95
    color #fff
    font-size 14px
    line-height 34px
    margin-left 33%
    margin-top 40px
    border-radius 5px
    padding-left 86px
    box-sizing border-box
    cursor pointer

  .disappear
    width 20px
    height 20px
    position absolute
    right 20px
    top 16px
    cursor pointer

  .disappear img
    height 20px

  #disappear-box
    width 600px
    height 430px
    background-color #fff
    position fixed
    left 50%
    top 50%
    margin-left -300px
    margin-top -215px
    z-index 999
    display none
    border-radius 10px

  .registered
    width 198px
    height 34px
    background-color #008F95
    border-radius 5px
    color #fff
    text-align center
    line-height 34px
    cursor pointer
    margin 0 auto
</style>
